package com.atmilan.quartz.utils.source;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.BuyerProduct;
import com.atmilan.quartz.model.entity.buyer.BuyerProductSkuMerged;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.result.PriceResult;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.service.ISystemAttachmentService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.util.StringUtil;

/**
 * 处理源数据转换和计算相关信息
 * @Description: 
 * @author daigb
 * @date 2021-03-05
 */
@Service
public class SourceBuyerProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;
    @Autowired
    ISystemAttachmentService systemAttachmentService;

    /**
     * 构建DO对象
     * @Description:  
     * @author daigb 
     * @param @param product
     * @param @param productSkus
     * @param @return
     * @return StoreProductRequest
     * @throws
     */
    public StoreProductCrmebRequest buildCrmebProduct(BuyerProduct product, List<BuyerProductSkuMerged> productSkus, String rateFloat, String rate, String rateCost) {
        // 源成本价
        BigDecimal erpPrice = new BigDecimal(product.getErpPrice());
        // 销售价(计算后)
//        BigDecimal adjustPrice = priceUtil.calePrice(new BigDecimal(rateFloat).multiply(erpPrice), rate);
        BigDecimal adjustPrice = erpPrice;
        // 成本价(计算后)
//        BigDecimal adjustCost = priceUtil.calePrice(erpPrice, rateCost);
        BigDecimal adjustCost = erpPrice;
        // 活动价
        BigDecimal promotePrice = null == product.getPromotePrice() ? BigDecimal.ZERO : new BigDecimal(product.getPromotePrice());
        BigDecimal originalPrice = null == product.getOriginalPrice() ? BigDecimal.ZERO : new BigDecimal(product.getOriginalPrice());
        // 品牌对应
        StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                .eq(StoreBrand :: getOtherId, product.getBrandId())
                .eq(StoreBrand :: getType, ProductTypeEnum.BUYER)
                .last("LIMIT 1")
                );
        storeBrandService.unMatchBrand(buyerStoreBrand,product.getBrandId(),product.getBrandName(),ProductTypeEnum.BUYER);
        StoreBrand storeBrand = null;
        if(null != buyerStoreBrand && null != buyerStoreBrand.getSuperId()) {
            storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
        }else {
            storeBrand = storeBrandService.getById(5429);
        }
        // 处理单独品牌价格(无法做成配置的)
        StoreProductCrmebRequest productRequest = new StoreProductCrmebRequest();
        if(null != storeBrand && "13De Marzo".equals(storeBrand.getEnName())) {
        	PriceResult priceResult = priceUtil.eur2Rmb(new BigDecimal(product.getOriginalPrice()));
            adjustPrice = PriceUtil.calePrice(priceResult.getPrice(), "0.65");
            productRequest.setExchangeRate(priceResult.getExchangeRate());
        }
        
        /***** 处理对象构建 *******/
        List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
        List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();
        // 规格
        StoreProductAttr storeProductAttr = new StoreProductAttr();
        storeProductAttr.setAttrName("尺寸");
        storeProductAttr.setType(0);
        // 颜色
        StoreProductAttr storeProductAttrColor = new StoreProductAttr();
        storeProductAttrColor.setAttrName("颜色");
        storeProductAttrColor.setType(0);
        String goodsImg = product.getGoodsImg();
        // 合并成suk
        List<String> colorValueList = new ArrayList<String>();
        List<String> valueList = new ArrayList<String>();
        for(BuyerProductSkuMerged buyerProductSku : productSkus) {
            StoreProductAttrValueRequest storeProductAttrValueRequest = new StoreProductAttrValueRequest();
            storeProductAttrValueRequest.setSourceSkuId(buyerProductSku.getSkuId());
            storeProductAttrValueRequest.setPromotePrice(promotePrice);
            storeProductAttrValueRequest.setPrice(adjustPrice);
            storeProductAttrValueRequest.setStock(buyerProductSku.getStock());
            storeProductAttrValueRequest.setOtPrice(originalPrice);
            storeProductAttrValueRequest.setCost(adjustCost);
            storeProductAttrValueRequest.setSourceCost(erpPrice);
            storeProductAttrValueRequest.setImage(systemAttachmentService.clearPrefix(goodsImg));

            LinkedHashMap<String, String> linkedMap = new LinkedHashMap<String, String>();
            List<String> suk = new ArrayList<String>();
            String color = buyerProductSku.getColor();
            if (StringUtils.isNotBlank(color)) {
                linkedMap.put("颜色", color);
                if(!colorValueList.contains(color)){
                    colorValueList.add(color);
                }
                suk.add(color);
            }
            String size = buyerProductSku.getSize();
            if (StringUtils.isNotBlank(size)) {
                linkedMap.put("尺寸", size);
                if(!valueList.contains(size)){
                    valueList.add(size);
                }
                suk.add(size);
            }
            storeProductAttrValueRequest.setSuk(String.join(",", suk));
            storeProductAttrValueRequest.setAttrValue(linkedMap);
            storeProductAttrValueRequest.setTempId(product.getStockArea());
            attrValueList.add(storeProductAttrValueRequest);
        }
        if (CollectionUtils.isNotEmpty(colorValueList)) {
            storeProductAttrColor.setAttrValues(String.join(",", colorValueList));
            attrList.add(storeProductAttrColor);
        }
        if (CollectionUtils.isNotEmpty(valueList)) {
            storeProductAttr.setAttrValues(String.join(",", valueList));
            attrList.add(storeProductAttr);
        }
        
        // 抽取所有size属性去重
        productRequest.setAttr(attrList);
        productRequest.setAttrValue(attrValueList);
        // 强制写一个 商户id 作为buyer商品标识标识
        productRequest.setMerId(CrmebMerchantEnums.BUYER.getMerchantId());
        productRequest.setContent(product.getGoodsCaizhi());
        productRequest.setKeyword(product.getGoodsCode());
        productRequest.setStoreInfo(product.getGoodsCaizhi());
        productRequest.setStoreName(product.getGoodsName());
        if(null != storeBrand) {
            productRequest.setBrandId(storeBrand.getId());
            productRequest.setBrandName(storeBrand.getEnName());
        }
//        productRequest.setTmall(product.getTmall());
        productRequest.setPostage(new BigDecimal(product.getShippingFee()));
        productRequest.setPrice(adjustPrice);
        productRequest.setPromotePrice(promotePrice);
        productRequest.setOtPrice(originalPrice);
        productRequest.setCost(adjustCost);
        productRequest.setSourceCost(erpPrice);
        productRequest.setPromoteFlag(false);
        productRequest.setErpPromFlag(true);

        // 供应商
        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                .eq(Supplier :: getSuppliersName, product.getSuppliersId())
                .last("LIMIT 1")
                );
        if(null != supplier) {
            productRequest.setSuppliersId(supplier.getId());
            productRequest.setSuppliersName(supplier.getSuppliersName());
            productRequest.setBarCode(BarCodeEnum.BUYER.getCode() + product.getGoodsId());
        } else {
        	productRequest.setSuppliersId(170);
        	productRequest.setSuppliersName(CrmebMerchantEnums.BUYER.getMerchantName());
        	productRequest.setBarCode(BarCodeEnum.BUYER.getCode() + product.getGoodsId());
        }

        CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                .eq(CategoryMatch :: getType, CategoryTypeEnum.BUYER)
                .eq(CategoryMatch :: getOthCategoryId, product.getCatId())
                .last("LIMIT 1")
                );
        categoryMatchService.unMatchCategory(categoryMatch,product.getCatId().toString(),product.getCatName(),null,CategoryTypeEnum.BUYER);
        // 复制重量
        if(null != categoryMatch) {
        	CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
        	categoryMatch.setWeight(Optional.ofNullable(supCategoryMatch).orElse(new CategoryMatch()).getWeight());
        }
        Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 1859;
        productRequest.setCateId(categoryId);
        productRequest.setCateIds(Arrays.asList(categoryId));
        productRequest.setWeight(null != categoryMatch ? categoryMatch.getWeight() : BigDecimal.ONE);
        productRequest.setImage(goodsImg);
        String galleryStr = product.getGallery();
        if(StringUtil.isNotEmpty(galleryStr)) {
            JSONArray arr = (JSONArray) JSONArray.parse(galleryStr);
            List<String> sliderImages = new ArrayList<String>();
            if (arr != null && arr.size() > 0) {
                arr.forEach(val -> {
                    JSONObject json = (JSONObject) val;
                    sliderImages.add(String.valueOf(json.get("img_original")));
                });
            }
            productRequest.setSliderImage(JSONObject.toJSONString(sliderImages));
        }
        productRequest.setIsShow(true);
        productRequest.setSort(0);
        productRequest.setSpecType(true);
        productRequest.setIsEurope(ProductTypeEnum.BUYER.getCode());
        productRequest.setTempId(product.getStockArea());
        productRequest.setUnitName("件");
        productRequest.setLastPushTime(new Date());
        if (StringUtils.isNotBlank(product.getSuppliersId()) && "2".equals(product.getSuppliersId())) {
            productRequest.setMerUse(true);
        }
        productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        productRequest.setImage(systemAttachmentService.clearPrefix(productRequest.getImage()));
        productRequest.setSliderImage(systemAttachmentService.clearPrefix(productRequest.getSliderImage()));
        
        return productRequest;
    }
    
}
